package com.example.touch_demo.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;


import com.example.touch_demo.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class SignatureView extends View {
    public static final String TAG = "asdf";
    private Path mPath = new Path();
    private Paint mPaint = new Paint();
    //位图的绘制内容输出者：画布
    private Canvas mCanvas;
    //用来存放绘制内容的位图
    private Bitmap mCacheBitmap;
    //上下文
    private Context mContext;
    //这个值通常用于确定多点触控中的"接近度"阈值，即当两个触摸点的距离小于这个阈值时，可以认为它们是同一个触摸点
    private static final float TOUCH_TOLERANCE = 4;

    // 新增一个列表来存储每个触摸点的路径
    private List<Path> paths = new ArrayList<>();
    private List<Float> lastX = new ArrayList<>();
    private List<Float> lastY = new ArrayList<>();
    public SignatureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(getResources().getColor(R.color.red, null));


    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCacheBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mCacheBitmap);
        mCanvas.drawColor(Color.WHITE);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();
        int pointerIndex = event.getActionIndex();
        float x = event.getX(pointerIndex);
        float y = event.getY(pointerIndex);

        // 根据触摸事件更新路径
        switch (action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                // 为新的触摸点创建一个新的路径
                Path newPath = new Path();
                newPath.moveTo(x, y);
                paths.add(newPath);
                lastX.add(x);
                lastY.add(y);
                break;
            case MotionEvent.ACTION_MOVE:
                // 更新所有活动的路径
                for (int i = 0; i < paths.size(); i++) {
                    if (event.getPointerId(i) == event.getPointerId(pointerIndex)) {
                        paths.get(i).lineTo(x, y);
                        lastX.set(i, x);
                        lastY.set(i, y);
                        break; // 只更新当前活动的触摸点
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                // 当手指抬起时，不需要做任何操作，因为我们只更新活动的路径
                break;
        }

        // 重新绘制所有路径
        for (Path path : paths) {
            mCanvas.drawPath(path, mPaint);
        }
        invalidate(); // 通知View重绘
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 绘制缓存的位图到画布上
        canvas.drawBitmap(mCacheBitmap, 0, 0, null);
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                mPath.moveTo(event.getX(), event.getY());
//                Log.e(TAG, "ACTION_DOWN getX = " + event.getX() + " getY = " + event.getY());
//                break;
//            case MotionEvent.ACTION_MOVE:
//                mPath.lineTo(event.getX(), event.getY());
//                Log.e(TAG, "ACTION_MOVE getX = " + event.getX() + " getY = " + event.getY());
//                break;
//            case MotionEvent.ACTION_UP:
//                Log.e(TAG, "ACTION_UP getX = " + event.getX() + " getY = " + event.getY());
//                break;
//        }
//        //真正负责绘制签名笔迹的画布，在这里接收路径mPath，以及事先定义好的颜料
//        mCanvas.drawPath(mPath, mPaint);
//        invalidate();
//        return true;
//    }



//    @Override
//    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
//        Log.e(TAG, "onDraw canvas = " + canvas);
//        canvas.drawPath(mPath, mPaint);
//    }

    /**
     * 清空
     */
    public void clear() {
        Log.e(TAG, "clear()");
        if (mPath != null) {
            Log.e(TAG, "before clear mPath isEmpty => " + mPath.isEmpty());
            mPath.reset();
            mCanvas.drawColor(Color.WHITE);
            Log.e(TAG, "after clear mPath isEmpty => " + mPath.isEmpty());
            invalidate();
        }
    }

    public void save() {
        //创建一个文件用于存放图片
        File file = new File(mContext.getExternalFilesDir(null) + "testSign.png");
        if (file.exists()) {
            file.delete();
        }
        OutputStream outputStream = null;
        try {
            //输出到这个文件
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(mContext, "保存异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        //压缩形成输出流
        mCacheBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        Toast.makeText(mContext, "保存成功!path:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    }

    public void saveImageToGallery() {
        String savedImageURL = MediaStore.Images.Media.insertImage(
                mContext.getContentResolver(),
                mCacheBitmap,
                "testSign",
                "testSign save"
        );
        Toast.makeText(mContext, "保存成功! URL:" + savedImageURL, Toast.LENGTH_SHORT).show();
    }
}
